package edu.zju.gis.dbfg.queryserver.controller;

import com.google.gson.JsonObject;
import edu.zju.gis.dbfg.common.Page;
import edu.zju.gis.dbfg.common.Result;
import edu.zju.gis.dbfg.queryserver.model.SearchResult;
import edu.zju.gis.dbfg.queryserver.model.vo.FeatureRecord;
import edu.zju.gis.dbfg.queryserver.model.vo.FeatureRecordsWithTotalSize;
import edu.zju.gis.dbfg.queryserver.service.AttributeQueryService;
import edu.zju.gis.dbfg.queryserver.tool.FormatUtil;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import static edu.zju.gis.dbfg.queryserver.constant.LimitedFieldsName.NO_SCROLL;

@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/attQuery")
public class AttributeQueryController {
    @Autowired
    AttributeQueryService attributeQueryService;

    @RequestMapping(value = "/view/{indexName}", method = RequestMethod.POST)
    public Result viewFrom2Size(@PathVariable String indexName, int pageSize, int pageNo) {
        //PageNo start with 1
        int fromIndex = (pageNo - 1) * pageSize;
        SearchResult result = attributeQueryService.selectByFromSize(indexName, fromIndex, pageSize);
        long totalSize = attributeQueryService.selectTotalSize(indexName);
        FeatureRecordsWithTotalSize res = new FeatureRecordsWithTotalSize();
        res.setRecords(FormatUtil.SearchResult2Records(result, false));
        res.setTotalSize(totalSize);
        return Result.success().setBody(res);
    }

    @RequestMapping(value = "/view/{indexName}/{tag}", method = RequestMethod.POST)
    public Result view(@PathVariable String indexName, @PathVariable String tag) {
        String scroll = tag.equals("0") ? NO_SCROLL : tag;
        SearchResult result = attributeQueryService.selectByScroll(indexName, scroll, 100);
        return Result.success().setBody(FormatUtil.SearchResult2RecordsWithScroll(result, false));
    }

    @RequestMapping(value = "/locate/{indexName}/{docId}", method = RequestMethod.POST)
    public Result locate(@PathVariable String indexName, @PathVariable String docId) {
        SearchResult result = attributeQueryService.selectByDocId(indexName, docId);
        return Result.success().setBody(FormatUtil.SearchResult2GeoJSON(result));
    }

    @RequestMapping(value = "/{indexName}", method = RequestMethod.POST)
    public Result highlight(@PathVariable String indexName, String field, String val) {
        SearchResult result = attributeQueryService.selectByField(indexName, field, val);
        return Result.success().setBody(FormatUtil.SearchResult2Records(result, false));
    }

}
